import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../resources/kq_theme_colors.dart';

import 'kq_reorderable_wrap.dart';

/// 网格拖拽排序菜单
///
/// @author 周卓
///
class KqDragGridView extends StatefulWidget {
  /// 列数，必须>0
  final int columnCount;

  /// 控件之间的间隔，默认10
  final double spacing;

  /// 四周间隔，默认0
  final double padding;

  /// 背景颜色
  final Color? backgroundColor;

  /// 拖拽回调，建议使用[Widget.Key]来唯一标识控件，从而拿到排序后的结果
  final Function(int oldIndex, int newIndex, List<Widget> children)?
      onDragComplete;

  /// 子控件
  final List<Widget> Function(double widgetWidth) widgetsBuilder;

  const KqDragGridView(
      {Key? key,
      required this.columnCount,
      this.spacing = 10,
      this.padding = 0,
      this.backgroundColor,
      required this.widgetsBuilder,
      this.onDragComplete})
      : super(key: key);

  @override
  KqDragGridViewState createState() => KqDragGridViewState();
}

class KqDragGridViewState extends State<KqDragGridView> {
  double widgetWidth = 0;

  List<Widget> children = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  void didUpdateWidget(covariant KqDragGridView oldWidget) {
    super.didUpdateWidget(oldWidget);
    widgetWidth = (context.width -
            widget.padding * 2 -
            widget.spacing * (widget.columnCount - 1)) /
        widget.columnCount;
    children = widget.widgetsBuilder(widgetWidth);
  }

  @override
  Widget build(BuildContext context) {
    if (children.isEmpty) {
      widgetWidth = (context.width -
              widget.padding * 2 -
              widget.spacing * (widget.columnCount - 1)) /
          widget.columnCount;
      children = widget.widgetsBuilder(widgetWidth);
    }
    return Container(
      color: widget.backgroundColor ?? KqThemeColors.bgWhite,
      child: KqReorderableWrap(
        spacing: widget.spacing,
        runSpacing: widget.spacing,
        padding: EdgeInsets.all(widget.padding),
        minMainAxisCount: widget.columnCount,
        maxMainAxisCount: widget.columnCount,
        onReorder: (int oldIndex, int newIndex) {
          if (widget.onDragComplete != null) {
            widget.onDragComplete!(oldIndex, newIndex, children);
          }
        },
        children: children,
      ),
    );
  }
}
